package com.monitor.distort.manager;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import org.apache.commons.io.FileUtils;

import com.monitor.distort.bean.DistortParam;
import com.monitor.distort.util.WgetConfig;
import com.monitor.util.command.CommandFactory;
import com.monitor.util.command.ISysCommand;

public class WgetManager {
	
	public WgetManager(){
		
	}
	
	public WgetManager(DistortParam distortParam) throws Exception{
		
		//判断任务是否存在
		if( isDistortProcessExist(distortParam) ){
			return;
		}
		
		waitWgetWebQueue.offer(distortParam);
	}
	
	/**
	 * 正在执行的wget队列
	 */
	public static Queue<DistortParam> runningWgetWebQueue   = new LinkedList<DistortParam>();     
	/**
	 * 等待wget的网站队列
	 */
	public static Queue<DistortParam> waitWgetWebQueue        = new LinkedList<DistortParam>();	 
	/**
	 * wget执行完成未进行处理的网站
	 */
	public static Queue<DistortParam> finishWgetWebQueue      = new LinkedList<DistortParam>();	  
	
	/**
	 * 扫描已完成的wget命令
	 * @throws Exception
	 */
	public void addFinishWebUrl() throws Exception{
		if(runningWgetWebQueue == null || runningWgetWebQueue.size() < 1)return;
		
		List<String> processInfoList = CommandFactory.getProcessInfoByName("wget");
		
		//添加执行完成的链接
		for(DistortParam distortParam: runningWgetWebQueue){
			String url = distortParam.getWeburl();
			boolean isfinish = true;
			for(String processInfo: processInfoList){
				if( processInfo.indexOf(url) != -1 ){
					isfinish = false;
					break;
				}
			}
			if(isfinish){
				finishWgetWebQueue.offer(distortParam);
			}
		}
		
		//删除上一次查看的已完成的wget信息
		for(DistortParam distortParam: finishWgetWebQueue){
			runningWgetWebQueue.remove(distortParam);
		}
	}
	
	/**
	 * 添加wget命令
	 * @throws Exception
	 */
	public void addWgetInfo() throws Exception{
		//判断runningWgetWebQueue是否个数为10；小于10则添加相关信息
		if(runningWgetWebQueue != null && runningWgetWebQueue.size() < WgetConfig.wgetLimit){
			
			int currWgetAmount = runningWgetWebQueue.size();
			int remainWgetAmount = WgetConfig.wgetLimit - currWgetAmount;
			for(int i = 0; i < remainWgetAmount; i ++){
				if(waitWgetWebQueue == null || waitWgetWebQueue.size() < 1){
					return;
				}
				
				DistortParam distortParam= waitWgetWebQueue.poll();
				
				//判断是否需要Wget
				if(1 != distortParam.getNeedWget()){
					finishWgetWebQueue.offer(distortParam);
					remainWgetAmount += 1;
					continue;
				}
				
				String weburl = distortParam.getWeburl();
				//判断wget是否存在
				boolean wgetexist = isWgetExist(weburl);
				
				try{
					if(!wgetexist){//不存在wget则执行
						//执行wget命令
						StringBuffer cmdBuff = new StringBuffer("wget –convert-links -rq -k -l 2  -t 3 -T 10  -P ")
							.append(WgetConfig.newPath)
							.append(" -N ").append( weburl )
							.append(" -U \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20100101 Firefox/23.0\"");
						
						ISysCommand command = CommandFactory.createCommand( cmdBuff.toString() );
				        command.excute();
					} else{
						remainWgetAmount += 1;//因为wget个数未增加
					}
					
					//添加信息
					runningWgetWebQueue.offer( distortParam );
				}catch(Exception e){
					waitWgetWebQueue.offer( distortParam );
					throw e;
				}
			}
		}
		//
	}
	
	/**
	 * 执行wget的后续工作
	 * 1、获取已完成wget的队列
	 * 2、判断现有执行的distortdetect个数
	 * @throws Exception 
	 */
	public void runFinishWebUrl() throws Exception{
		if(finishWgetWebQueue == null || finishWgetWebQueue.size() < 1)return;
		
		while(finishWgetWebQueue.size() > 0){
			int distortProcessAmount = CommandFactory.getProcessAmountByName(WgetConfig.distortDetectName);//WgetConfig.distortDetectName
			//判断线程个数,如果执行线程个数超过限制，则跳过，等待下一轮的定时任务执行
			if(distortProcessAmount > WgetConfig.distortProcessLimit) {
				return;
			}
			
			DistortParam distortParam = finishWgetWebQueue.poll();
			
			try{
				//运行监测程序distortDetect.jar
				runDistortDetect(distortParam);
				
			}catch(Exception e){
				finishWgetWebQueue.offer(distortParam);
			}
			
		}
	}
	
	public boolean isWgetExist(String weburl) throws Exception{
		
		List<String> processInfoList = CommandFactory.getProcessInfoByName("wget");
		
		//添加执行完成的链接
		for(String processInfo: processInfoList){
			if( processInfo.indexOf( weburl ) != -1 ){
				return true;
			}
		}
		return false;
	}
	
	public boolean isDistortProcessExist(DistortParam distortParam) throws Exception{
		String scanid = distortParam.getScanid();
		
		StringBuffer commandStr = new StringBuffer(WgetConfig.distortDetectName)
				.append(" -scanid ").append( scanid );
		
		List<String> processInfoList = CommandFactory.getProcessInfoByName( commandStr.toString() );
		
		if(processInfoList != null && processInfoList.size() > 0){
			return true;
		}else{
			return false;
		}
	}
	
	public void runDistortDetect(DistortParam distortParam) throws Exception{
		StringBuffer commandStr = new StringBuffer("java -jar ").append(WgetConfig.distortDetectName)
										.append(" -scanid ").append( distortParam.getScanid() )
										.append(" -weburl ").append( distortParam.getWeburl() )
										.append(" -needWget ").append( distortParam.getNeedWget() );
		
		Runtime runtime = Runtime.getRuntime();

        try {
            File file = new File(WgetConfig.distortDetectPath);
            runtime.exec(commandStr.toString(), null, file); //开启新进程执行命令
        } catch (IOException e) {
        	e.printStackTrace();
        }
	}
	
	public static void main(String[] args) throws Exception{
		//运行定时任务
		JobManager.runJobList();
		
		List<String> urlList = FileUtils.readLines(new File(args[0]), "UTF-8");
		//创建对象开始扫描
		
		while(true){
			if(waitWgetWebQueue.size() > 0){
				Thread.sleep(10*60*1000);
				continue;
			}
			for(String str : urlList){
				DistortParam distortParam = new DistortParam();
				distortParam.setScanid(String.valueOf(System.currentTimeMillis()));
				distortParam.setWeburl(str);
				distortParam.setNeedWget(1);
				WgetManager wgetManager = new WgetManager(distortParam);
			}
		}
	}
}
